package com.ahdy.mapper;

import com.ahdy.entity.ElderlyFamilyRelation;
import org.apache.ibatis.annotations.*;

import java.util.List;

// 3. 关联关系Mapper
@Mapper
public interface ElderlyFamilyRelationMapper {

    @Insert("INSERT INTO elderly_family_relations(elderly_id, family_id, relation_type, created_at, updated_at) " +
            "VALUES(#{elderlyId}, #{familyId}, #{relationType}, #{createdAt}, #{updatedAt})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(ElderlyFamilyRelation relation);

    @Update("UPDATE elderly_family_relations SET relation_type=#{relationType}, updated_at=#{updatedAt} WHERE id=#{id}")
    int update(ElderlyFamilyRelation relation);

    @Delete("DELETE FROM elderly_family_relations WHERE id=#{id}")
    int deleteById(Integer id);

    @Delete("DELETE FROM elderly_family_relations WHERE elderly_id=#{elderlyId} AND family_id=#{familyId}")
    int deleteByElderlyAndFamily(@Param("elderlyId") Integer elderlyId, @Param("familyId") Integer familyId);

    @Select("SELECT * FROM elderly_family_relations WHERE id=#{id}")
    ElderlyFamilyRelation findById(Integer id);

    @Select("SELECT * FROM elderly_family_relations WHERE elderly_id=#{elderlyId}")
    List<ElderlyFamilyRelation> findByElderlyId(Integer elderlyId);

    @Select("SELECT * FROM elderly_family_relations WHERE family_id=#{familyId}")
    List<ElderlyFamilyRelation> findByFamilyId(Integer familyId);

    @Select("SELECT * FROM elderly_family_relations WHERE elderly_id=#{elderlyId} AND family_id=#{familyId}")
    ElderlyFamilyRelation findByElderlyAndFamily(@Param("elderlyId") Integer elderlyId, @Param("familyId") Integer familyId);

    // 检查关联关系是否存在
    @Select("SELECT COUNT(*) FROM elderly_family_relations WHERE elderly_id=#{elderlyId} AND family_id=#{familyId}")
    int countByElderlyAndFamily(@Param("elderlyId") Integer elderlyId, @Param("familyId") Integer familyId);
}
